#!/bin/bash

CPATH=$(cd `dirname $0`;pwd)
TOOLS="$CPATH/../lib"
source $TOOLS/lib.sh
source ./config.sh

log_info "Start: $0 $@"
if [ $# -eq 2 ];then
    OBSSERVER_IP=$1
    PASSWD=$2
else
    log_error "Usage: $0 OBSSERVER_IP PASSWD"
fi

set -e

repo_dir="/usr1/jenkins/EulerOS_${GERRIT_BRANCH}"
obs_repo_dir='/srv/obs/build/CentOS7.5:Updates/standard'
pushd ${repo_dir}
bash ${CPATH}/repo_pull.sh ${MANIFEST} ${GERRIT_PROJECT}
pushd ${repo_dir}/euleros/tools/obs_bin/

while read line
do
    mode=$(echo ${line} | awk '{print $1}')
    file_path=$(echo ${line} | awk '{print $2}')
    arch=''
    if echo ${file_path} | grep x86_64; then
        arch="x86_64"
    elif echo ${file_path} | grep i686; then
        arch="i686"
    elif echo ${file_path} | grep aarch64; then
        arch="aarch64"
    elif echo ${file_path} | grep armv7l; then
        arch="armv7l"
    fi
    if [ -z "${arch}" ];then
        echo "arch be required"
        exit 1
    fi
    if [[ ${mode} == A* ]];then
        pushd ..
        bash ${TOOLS}/sshscp.sh -p "$PASSWD" -s obs_bin/${file_path} -d "${OBSSERVER_IP}:${obs_repo_dir}/${arch}/:full/"
        popd
        bash ${TOOLS}/sshcmd.sh -c "cd ${obs_repo_dir};chmod 644 ${arch}/:full/*;cd /srv/obs/build/;/usr/lib/obs/server/bs_admin --rescan-repository CentOS7.5:Updates standard ${arch} || exit 1" -m "$OBSSERVER_IP" -u "root" -p "$PASSWD"
        echo "upload ${file_path} to ${OBSSERVER_IP} success"
    elif [[ ${mode} == D* ]];then
        file_name=$(echo ${file_path} | awk -F '/' '{print $NF}')
        bash ${TOOLS}/sshcmd.sh -c "cd ${obs_repo_dir}/${arch}/:full/;rm ${file_name};cd /srv/obs/build/;/usr/lib/obs/server/bs_admin --rescan-repository CentOS7.5:Updates standard ${arch} || exit 1" -m "$OBSSERVER_IP" -u "root" -p "$PASSWD"
        echo "delete ${file_path} from ${OBSSERVER_IP} success"
    elif [[ ${mode} == R* ]];then
        old_file_name=$(echo ${file_path} | awk -F '/' '{print $NF}')
        new_file_name=$(echo ${line} | awk '{print $3}' | awk -F '/' '{print $NF}')
        bash ${TOOLS}/sshcmd.sh -c "cd ${obs_repo_dir}/${arch}/:full/;mv ${old_file_name} ${new_file_name};cd /srv/obs/build/;/usr/lib/obs/server/bs_admin --rescan-repository CentOS7.5:Updates standard ${arch} || exit 1" -m "$OBSSERVER_IP" -u "root" -p "$PASSWD"
        echo "rename ${old_file_name} to ${new_file_name} on ${OBSSERVER_IP} success"
    fi
done< <(git diff --name-status ${GERRIT_PATCHSET_REVISION}~ ${GERRIT_PATCHSET_REVISION})